package com.gloaba.gateway.filter;


import com.gloaba.common.core.constant.HttpStatus;
import com.gloaba.common.core.constant.SecurityConstants;
import com.gloaba.common.core.utils.ServletUtils;
import com.gloaba.common.core.utils.StringUtils;
import com.gloaba.gateway.config.properties.IgnoreWhiteProperties;
import com.gloaba.gateway.utils.WebFluxUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.gloaba.gateway.config.properties.SecurityProperties;

/**
 * 网关鉴权
 *
 * @author Zane
 */
@Component
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    private final IgnoreWhiteProperties ignoreWhite;

    private final SecurityProperties securityProperties;



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        if(!securityProperties.getEnbled()){
            //不做校验
            return chain.filter(exchange);
        }

        String path = request.getURI().getPath();

        // 跳过不需要验证的路径
        if (StringUtils.matches(path, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        //校验token


        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return WebFluxUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }


    @Override
    public int getOrder() {
        return -200;
    }
}
